package com.qf.filter;


import com.qf.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


//对showAllController进行控制
@WebFilter("/index.jsp")
public class CheckLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //获取session  因为session是有协议的 当前req没有协议  需要强转为有协议的
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //2.通过request获取session
        HttpSession session = request.getSession();

        //在session中获取user  查看是否登录
        User user = (User) session.getAttribute("user");
        if (user != null) {
            //不等等于null 就代表已经登录了
            //已经登录 就放行
            chain.doFilter(req, resp);
        } else {
            //反之等于null代表没有登录 返回登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        }
    }


    public void init(FilterConfig config) throws ServletException {
    }

}
